//
//  ContentView.swift
//  ALLocation
//
//  Created by 云控蜂核 on 2023/5/6.
//

import SwiftUI

import CoreLocation
import CoreLocationUI
import MapKit

struct ContentView: View {
    
    @StateObject var locationManager = LocationManager()
    
    
    var body: some View {
        
        
        ZStack(alignment: .bottomTrailing) {
            
            Map(coordinateRegion: $locationManager.region, showsUserLocation: true, annotationItems: locationManager.coffeeShop) { shop in
                MapMarker(coordinate: shop.mapItem.placemark.coordinate, tint: .purple)
            }
            
            Map(coordinateRegion: $locationManager.region, showsUserLocation: true)
                .ignoresSafeArea()
            
            LocationButton(.currentLocation) {
                locationManager.manager.requestLocation()
            }
            .symbolVariant(.fill)
            .foregroundColor(.white)
            .tint(.purple)
            .clipShape(Capsule())
            .padding()
        }
        
        .overlay(alignment: .top) {
            Text("coffe shop's")
                .font(.title.bold())
                .frame(maxWidth: .infinity, alignment: .leading)
                .padding()
                .background(.ultraThinMaterial)
        }
        //overlay or background will automatically fill safe area
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate{
    @Published var manager = CLLocationManager()
    @Published var region: MKCoordinateRegion = .init()
    @Published var coffeeShop: [Shop] = []
    
    
    override init() {
        super.init()
        manager.delegate = self
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error.localizedDescription)
    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        guard let location = locations.last?.coordinate else{
            return
        }
        region = MKCoordinateRegion(center: location, latitudinalMeters: 1000, longitudinalMeters: 1000)
        
        Task{
            await fetchCoffeeShops()
        }
        
    }
    
    //sample location search aync task...
    func fetchCoffeeShops() async {
        do {
            let request = MKLocalSearch.Request()
            request.region = region
            request.naturalLanguageQuery = "coffee"
            
            let query = MKLocalSearch(request: request)
            
            let response = try await query.start()
            
            //you can also use dispatch quene...
            await MainActor.run {
                self.coffeeShop = response.mapItems.compactMap { item in
                    return Shop(mapItem: item)
                }
            }
            
        } catch {
            
        }
    }
    
    
}


// sample model for map pin

struct Shop: Identifiable{
    var id = UUID().uuidString
    var mapItem: MKMapItem
}
